// packageE/pages/orderBoard/index.js
// 状态映射文本
const statusMap = {
    pending: '未派单',
    taken: '已抢单',
    in_progress: '服务中',
    completed: '已完成',
    cancelled: '已取消'
};
Page({

    /**
     * 页面的初始数据
     */
    data: {
        statusFilters: [
            // { name: '全部', value: 'all' },
            { name: '待抢单', value: 'pending' },
            { name: '已接单', value: 'taken' },
            // { name: '服务中', value: 'in_progress' },
            { name: '已完成', value: 'completed' },
            { name: '已取消', value: 'cancelled' }
        ],
        activeStatus: 'pending',
        orders: [{
            acceptTime: "2025-09-18T21:03:17.015605",
            addTime: "2025-09-18T21:03:17.680869",
            adminRemark: null,
            auntPhone: "",
            caregiverId: 0,
            caregiverNickname: "",
            checkinPhoto: "",
            checkinTime: "2025-09-18T21:03:17.015605",
            city: "上海市",
            clientName: "吴茜茜",
            clientPhone: "13916690490",
            comment: "",
            detailAddress: "上海徐汇区，云锦路183弄13-703",
            dispatcherId: 603,
            dispatcherNickname: "",
            district: "徐汇区",
            flag: false,
            id: 62,
            lastUpdateTime: "2025-09-18T21:03:17.680869",
            latitude: 31.174304,
            longitude: 121.460145,
            notes: "专业的，拒绝差评。",
            price: 9,
            province: "上海",
            raterAvatarUrl: "",
            raterName: "",
            rateraccountId: 0,
            rating: 0,
            ratingTime: "2025-09-18T21:03:17.015605",
            remark: null,
            serviceContent: "奶皮子酸奶",
            serviceDate: "2025-09-17T00:00:00",
            serviceTime: "2025-09-18T09:00:00",
            serviceType: "奶皮子酸奶",
            status: "pending",
            statusText: "一键抢单",
            tenantId: 0
        },{
            acceptTime: "2025-09-18T21:03:17.015605",
            addTime: "2025-09-18T21:03:17.680869",
            adminRemark: null,
            auntPhone: "",
            caregiverId: 0,
            caregiverNickname: "",
            checkinPhoto: "",
            checkinTime: "2025-09-18T21:03:17.015605",
            city: "上海市",
            clientName: "吴茜茜",
            clientPhone: "13916690490",
            comment: "",
            detailAddress: "上海徐汇区，云锦路183弄13-703",
            dispatcherId: 603,
            dispatcherNickname: "",
            district: "徐汇区",
            flag: false,
            id: 62,
            lastUpdateTime: "2025-09-18T21:03:17.680869",
            latitude: 31.174304,
            longitude: 121.460145,
            notes: "专业的，拒绝差评。",
            price: 9,
            province: "上海",
            raterAvatarUrl: "",
            raterName: "",
            rateraccountId: 0,
            rating: 0,
            ratingTime: "2025-09-18T21:03:17.015605",
            remark: null,
            serviceContent: "奶皮子酸奶",
            serviceDate: "2025-09-17T00:00:00",
            serviceTime: "2025-09-18T09:00:00",
            serviceType: "奶皮子酸奶",
            status: "taken",
            statusText: "一键抢单",
            tenantId: 0
        },{
            acceptTime: "2025-09-18T21:03:17.015605",
            addTime: "2025-09-18T21:03:17.680869",
            adminRemark: null,
            auntPhone: "",
            caregiverId: 0,
            caregiverNickname: "",
            checkinPhoto: "",
            checkinTime: "2025-09-18T21:03:17.015605",
            city: "上海市",
            clientName: "吴茜茜",
            clientPhone: "13916690490",
            comment: "",
            detailAddress: "上海徐汇区，云锦路183弄13-703",
            dispatcherId: 603,
            dispatcherNickname: "",
            district: "徐汇区",
            flag: false,
            id: 62,
            lastUpdateTime: "2025-09-18T21:03:17.680869",
            latitude: 31.174304,
            longitude: 121.460145,
            notes: "专业的，拒绝差评。",
            price: 9,
            province: "上海",
            raterAvatarUrl: "",
            raterName: "",
            rateraccountId: 0,
            rating: 0,
            ratingTime: "2025-09-18T21:03:17.015605",
            remark: null,
            serviceContent: "奶皮子酸奶",
            serviceDate: "2025-09-17T00:00:00",
            serviceTime: "2025-09-18T09:00:00",
            serviceType: "奶皮子酸奶",
            status: "in_progress",
            statusText: "一键抢单",
            tenantId: 0
        },{
            acceptTime: "2025-09-18T21:03:17.015605",
            addTime: "2025-09-18T21:03:17.680869",
            adminRemark: null,
            auntPhone: "",
            caregiverId: 0,
            caregiverNickname: "",
            checkinPhoto: "",
            checkinTime: "2025-09-18T21:03:17.015605",
            city: "上海市",
            clientName: "吴茜茜",
            clientPhone: "13916690490",
            comment: "",
            detailAddress: "上海徐汇区，云锦路183弄13-703",
            dispatcherId: 603,
            dispatcherNickname: "",
            district: "徐汇区",
            flag: false,
            id: 62,
            lastUpdateTime: "2025-09-18T21:03:17.680869",
            latitude: 31.174304,
            longitude: 121.460145,
            notes: "专业的，拒绝差评。",
            price: 9,
            province: "上海",
            raterAvatarUrl: "",
            raterName: "",
            rateraccountId: 0,
            rating: 0,
            ratingTime: "2025-09-18T21:03:17.015605",
            remark: null,
            serviceContent: "奶皮子酸奶",
            serviceDate: "2025-09-17T00:00:00",
            serviceTime: "2025-09-18T09:00:00",
            serviceType: "奶皮子酸奶",
            status: "completed",
            statusText: "一键抢单",
            tenantId: 0
        }],
        page: 1,
        pageSize: 10,
        loading: false,
        noMore: false,
        pendingid: 0,
        role: null,
        orderId: 0,
        price: 0,
        detailAddress: ''
    },
    //获取我的积分是否够
    GetIntegralisOK(param) {
        return wx.Http.post('/IntegralAppService/GetIntegralisOK', { type: param })
    },
    tokenP() {
        return wx.Http.post('/AccountAppService/CheckmyUserPhone', {})
    },
    GetmyTalentPool() {
        return wx.Http.post('/TalentPoolAppService/GetmyTalentPool')
    },
    setMonkey(monkey, RewardCoinId, Title) {
        return wx.Http.post("/AccountAppService/UpdatemysysUserinfos", {
            integral: -monkey,
            rewardCoinId: RewardCoinId,
            title: Title,
        });
    },
    //获取积分多少
    GetIntegralpiceinfos(text) {
        return wx.Http.post("/IntegralAppService/GetIntegralpice", { type: text });
    },
    shareOrder(event) {
        this.setData({
            orderId: event.currentTarget.dataset.item.id,
            price: event.currentTarget.dataset.item.price,
            detailAddress: event.currentTarget.dataset.item.detailAddress
        })
    },
    //抢单（已经作废）
    async grabOrder(e) {
        const item = e.currentTarget.dataset.item;
        const _this = this;

        let res = await this.tokenP();

        if (!res.data) {
            wx.navigateTo({
                url: '/pages/user/login/index',
            })
        } else {
            var resTalentPoolInfo = await this.GetmyTalentPool();

            if (resTalentPoolInfo.data) {
                wx.Http.post("/ServiceOrderAPPService/TakenServiceOrder", {
                    Status: 'taken',
                    Id: item.id,
                    CaregiverId: resTalentPoolInfo.data.accountId,
                    CaregiverNickname: resTalentPoolInfo.data.name,
                    AuntPhone: resTalentPoolInfo.data.telephone,
                }).then((res) => {
                    if (res.data) {
                        _this.GetIntegralpiceinfos("接单").then((res) => {
                            var myjiangli = res.data;

                            _this.setMonkey(res.data, 0, "抢单扣积分").then((res) => {
                                if (res.data) {
                                    _this.setData({
                                        noMore: false,
                                        activeStatus: 'taken',
                                    }, () => {
                                        _this.loadOrders();
                                        wx.showToast({
                                            title: '抢单成功',
                                        })
                                        wx.showToast({
                                            title: '扣积分' + myjiangli + "个",
                                        })
                                    })

                                }
                            })
                        })
                        // _this.setData({
                        //     noMore: false
                        // }, () => {



                        // })
                    }

                })

            } else {
                wx.showModal({
                    title: '提示',
                    content: '填写简历',
                    complete: (res) => {
                        if (res.cancel) {

                        }

                        if (res.confirm) {
                            wx.navigateTo({
                                url: '/pages/Talent/rcjl/index',
                            })
                        }
                    }
                })


            }

        }

    },
    onAuntSelected(selectedAunt) {
        const _this = this;
        wx.Http.post("/ServiceOrderAPPService/TakenServiceOrder", {
            Status: 'taken',
            Id: this.data.pendingid,
            CaregiverId: selectedAunt.accountId,
            CaregiverNickname: selectedAunt.name,
            AuntPhone: selectedAunt.telephone,
        }).then((res) => {
            _this.setData({
                noMore: false
            }, () => {
                _this.loadOrders();
                wx.showToast({
                    title: '派单成功',
                })
            })
        })
        this.setData({
            caregiverId: selectedAunt.accountId,
            caregiverNickname: selectedAunt.name,
            auntPhone: selectedAunt.telephone,
        })
    },
    // 订单发布按钮点击事件
    releaseOrder() {
        this.GetIntegralisOK("家政订单发布").then((res) => {
            if (res.success) {
                if (res.data) {
                    wx.showToast({
                        title: '发布订单',
                        icon: 'success'
                    })
                    // 实际项目中这里跳转到订单发布页面
                    wx.navigateTo({ url: '/packageE/pages/createOrder/index' })
                } else {
                    wx.showModal({
                        title: '提示',
                        content: res.errorMessage,
                        complete: (res) => {
                            if (res.cancel) {

                            }

                            if (res.confirm) {
                                wx.navigateTo({
                                    url: '/pages/user/coinPay/coinPay',
                                })
                            }
                        }
                    })
                }
            }
        })

    },

    // 我要接单按钮点击事件
    async takeOrder() {
        const _this = this;
        await this.GetIntegralisOK("接单").then((res) => {
            if (res.data) {
                _this.tokenP().then((res) => {
                    if (!res.data) {
                        wx.navigateTo({
                            url: '/pages/user/login/index',
                        })
                    } else {
                        _this.GetmyTalentPool().then((res) => {
                            if (res.data) {
                                // 实际项目中这里跳转到接单大厅
                                wx.navigateTo({ url: '/packageE/pages/receptionHall/index' })

                            } else {
                                wx.showModal({
                                    title: '提示',
                                    content: '填写简历',
                                    complete: (res) => {
                                        if (res.cancel) {

                                        }

                                        if (res.confirm) {
                                            wx.navigateTo({
                                                url: '/pages/Talent/rcjl/index',
                                            })
                                        }
                                    }
                                })


                            }

                        })


                    }
                })


            } else {
                wx.showModal({
                    title: '提示',
                    content: res.errorMessage,
                    complete: (res) => {
                        if (res.cancel) {

                        }

                        if (res.confirm) {
                            wx.navigateTo({
                                url: '/pages/user/coinPay/coinPay',
                            })
                        }
                    }
                })

            }
        })


    },
    GetServiceOrdersinfo(param1, param2, param3) {
        // return wx.Http.get("/ServiceOrderAPPService/GetServiceOrders", {
        //     PageIndex: param1,
        //     PageCount: param2,
        //     Status: param3

        // });
    },
    CancelServiceOrder(param1, param2) {
        return wx.Http.post("/ServiceOrderAPPService/CancelServiceOrder", {
            id: param1,
            Status: param2
        });
    },
    DeleteServiceOrder(param1) {
        return wx.Http.post("/ServiceOrderAPPService/DeleteServiceOrder", {
            id: param1
        });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
        let role = null;
        role = wx.getStorageSync('role');
        if (role) {
            this.setData({
                role
            })
        }
        this.loadOrders();
        // this.setupWebSocket();
    },

    // 设置WebSocket连接
    setupWebSocket() {
        wx.connectSocket({
            url: 'wss://your-api-domain.com/order-ws'
        });

        wx.onSocketMessage(res => {
            const data = JSON.parse(res.data);
            switch (data.type) {
                case 'ORDER_CREATED':
                    this.handleNewOrder(data.payload);
                    break;
                case 'ORDER_UPDATED':
                    this.updateOrderStatus(data.payload);
                    break;
            }
        });
    },

    // 处理新订单
    handleNewOrder(order) {
        if (this.data.activeStatus === 'all' || this.data.activeStatus === 'pending') {
            const orders = [{
                ...order,
                statusText: statusMap[order.status] || order.status
            }, ...this.data.orders];
            this.setData({ orders });
        }
    },

    // 更新订单状态
    updateOrderStatus(updatedOrder) {
        const orders = this.data.orders.map(order => {
            if (order.id === updatedOrder) {
                debugger
                return {
                    ...order,
                    ...updatedOrder,
                    //   statusText: statusMap[updatedOrder.status] || updatedOrder.status
                    statusText: statusMap[order.status] || order.status
                };
            }
            return order;
        });

        this.setData({ orders });
    },

    // 切换筛选状态
    changeFilter(e) {
        const status = e.currentTarget.dataset.value;
        this.setData({
            activeStatus: status,
            page: 1,
            // orders: [],
            noMore: false
        }, () => this.loadOrders());
    },

    // 加载订单
    loadOrders() {
        // if (this.data.loading || this.data.noMore) return;
        // this.setData({ loading: true });
        // this.GetServiceOrdersinfo(this.data.page, this.data.pageSize, this.data.activeStatus).then((res) => {
        //     if (res.success) {
        //         const newOrders = res.data.list.map(order => ({
        //             ...order,
        //             statusText: statusMap[order.status] || order.status
        //         }));

        //         this.setData({
        //             orders: this.data.page === 1
        //                 ? newOrders
        //                 : [...this.data.orders, ...newOrders],
        //             noMore: newOrders.length < this.data.pageSize
        //         });
        //         this.setData({ loading: false });
        //     }
        // })
       
    },

    // 加载更多
    loadMore() {
        if (!this.data.noMore) {
            this.setData({ page: this.data.page + 1 }, () => this.loadOrders());
        }
    },

    // 派单操作
    assignOrder(e) {
        const item = e.currentTarget.dataset.item;
        this.setData({
            pendingid: item.id
        })
        wx.navigateTo({
            url: `/packageA/pages/chooseAunt/index?latitude=${item.latitude}` + '&longitude=' + item.longitude
        });
    },

    // 取消订单
    cancelOrder(e) {
        const _this = this;
        const orderId = e.currentTarget.dataset.id;
        wx.showModal({
            title: '确认取消',
            content: '确定要取消此订单吗？',
            success: res => {
                if (res.confirm) {
                    wx.showToast({
                        title: '取消成功',
                    })
                    // _this.CancelServiceOrder(orderId, 'cancelled').then((res) => {
                    //     _this.setData({
                    //         noMore: false
                    //     }, () => {
                    //         _this.loadOrders();
                    //     })
                    // })

                }
            }
        });
    },
    backOrder(e) {
        wx.navigateTo({
            url: '/packageE/pages/createOrder/index?id=' + e.currentTarget.dataset.id,
        })
    },
    contactclient(e) {
        const _this = this;
        const orderId = e.currentTarget.dataset.id;
        const order = this.data.orders.find(o => o.id === orderId);
        if (order && order.clientPhone) {
            this.GetIntegralisOK("接单后拨打电话").then((res) => {
                if (res.success) {
                    if (res.data) {

                        _this.GetIntegralpiceinfos("接单后拨打电话").then((res) => {
                            var myjiangli = res.data;
                            wx.showModal({
                                title: '提示',
                                content: '需要扣' + myjiangli + "个积分",
                                complete: (res) => {
                                    if (res.cancel) {

                                    }

                                    if (res.confirm) {
                                        _this.setMonkey(myjiangli, 0, "接单后拨打电话").then((res) => {
                                            if (res.data) {
                                                wx.showToast({
                                                    title: '扣积分' + myjiangli,
                                                })
                                                setTimeout(() => {
                                                    wx.makePhoneCall({
                                                        phoneNumber: order.clientPhone
                                                    });
                                                }, 1000);

                                            }
                                        })
                                    }
                                }
                            })



                        })

                    } else {
                        wx.showModal({
                            title: '提示',
                            content: res.errorMessage,
                            complete: (res) => {
                                if (res.cancel) {

                                }

                                if (res.confirm) {
                                    wx.navigateTo({
                                        url: '/pages/user/coinPay/coinPay',
                                    })
                                }
                            }
                        })
                    }
                }
            })

        }
    },
    // 联系阿姨
    contactAunt(e) {
        const _this = this;
        const orderId = e.currentTarget.dataset.id;
        const order = this.data.orders.find(o => o.id === orderId);
        if (order && order.auntPhone) {
            this.GetIntegralisOK("接单后拨打电话").then((res) => {
                if (res.success) {
                    if (res.data) {

                        _this.GetIntegralpiceinfos("接单后拨打电话").then((res) => {
                            var myjiangli = res.data;
                            wx.showModal({
                                title: '提示',
                                content: '需要扣' + myjiangli + "个积分",
                                complete: (res) => {
                                    if (res.cancel) {

                                    }

                                    if (res.confirm) {
                                        _this.setMonkey(myjiangli, 0, "接单后拨打电话").then((res) => {
                                            if (res.data) {
                                                wx.showToast({
                                                    title: '扣积分' + myjiangli,
                                                })
                                                setTimeout(() => {
                                                    wx.makePhoneCall({
                                                        phoneNumber: order.auntPhone
                                                    });
                                                }, 1000);

                                            }
                                        })
                                    }
                                }
                            })



                        })

                    } else {
                        wx.showModal({
                            title: '提示',
                            content: res.errorMessage,
                            complete: (res) => {
                                if (res.cancel) {

                                }

                                if (res.confirm) {
                                    wx.navigateTo({
                                        url: '/pages/user/coinPay/coinPay',
                                    })
                                }
                            }
                        })
                    }
                }
            })

        }
    },

    // 查看详情
    viewDetail(e) {
        const orderId = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: `/packageA/pages/order-detail/index?id=${orderId}`
        });
    },

    // 删除订单
    deleteOrder(e) {
        const _this = this;
        wx.showModal({
            title: '确认删除',
            content: '删除后将无法恢复，确定删除吗？',
            success: res => {
                if (res.confirm) {
                    const orderId = e.currentTarget.dataset.id;
                    _this.DeleteServiceOrder(orderId).then((res) => {
                        if (res.data) {
                            _this.setData({
                                noMore: false
                            }, () => {
                                _this.loadOrders();
                                wx.showToast({ title: '删除成功' });
                            })

                        }
                    })

                }
            }
        });
    },

    // 从列表中删除订单
    deleteOrderFromList(orderId) {
        const _this = this;
        wx.request({
            url: `https://your-api-domain.com/orders/${orderId}`,
            method: 'DELETE',
            success: res => {
                if (res.data.success) {
                    _this.loadOrders();
                    // const orders = this.data.orders.filter(o => o.id !== orderId);
                    // this.setData({ orders });
                    wx.showToast({ title: '删除成功' });
                }
            }
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})